<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入手机号码"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          :loading="isLoading"
        >登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from '@/services/user'
// import request from '@/utils/request'
// import qs from 'qs'
export default {
  name: 'Login',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '请输入6 到 18 位的密码', trigger: 'blur' }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      // this.$refs.form.validate((valid) => {})
      // 用aysnc和await来代替
      try {
        // 1、表单验证
        await this.$refs.form.validate()
        // 2、发送请求
        // 用解构的方式取出响应数据data
        // 验证通过后，开始请求数据时，按钮置为loading状态中
        this.isLoading = true
        const { data } = await login(this.form)
        // const { data } = await request({
        //   method: 'POST',
        //   url: '/front/user/login',
        //   data: qs.stringify(this.form)
        // })
        // 响应完成后，将按钮置于正常状态
        this.isLoading = false
        // 3、响应处理
        if (data.state !== 1) {
          // 响应失败时，提示失败，并中断
          return this.$message.error('登录失败')
        }
        // 将用户的信息储存到 Vuexz 中
        // 应该先存储再跳转路由，先拿到token再判断
        this.$store.commit('setUser', data.content)
        // 响应成功，跳转路由并提示成功
        // 根据可能存储的 redirect 数据进行跳转设置
        this.$router.push(this.$route.query.redirect || '/')
        this.$message.success('登录成功')
      } catch {
        console.log('校验不通过')
      }
    }
  }
}
</script>
<style lang="scss">
  .login {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    .el-form {
      background-color: #fff;
      padding: 40px;
      border-radius: 10px;
      .el-button {
        width: 100%;
      }
    }
  }
</style>
